﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using Zoomtel.Persist.BIZ;
using Zoomtel.Persist.Sms;
using Zoomtel.Utils;

namespace Zoomtel.Service.Sms
{
    public class SmsService
    {

        private SmsRepository _repository;
        private AgentInfoRepository _agentRepository;
        public SmsService(SmsRepository repository, AgentInfoRepository agentRepository)
        {
            _repository = repository;
            _agentRepository = agentRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="code"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetModelAndCp(string mobile, string code, string type)
        {
            Entity.Sms.SmsEntity model = _repository.FindEntity(a=>a.Mobile==mobile&&a.Code==code&&a.Type==type&&a.State==0);

            if (model != null)
            {
                if (DateTime.Now < model.Endtime)
                {
                    model.State = 1;
                    int i = _repository.Update(model);
                    if (i == 1)
                    {

                        return "ok";
                    }
                    else
                    {
                        return "短信验证码验证失败";
                    }
                }
                else
                {

                    return "验证码超时";
                }

            }
            else
            {

                return "无效的验证码";
            }
        }

        /**
              * 使用AK&SK初始化账号Client
              * @param accessKeyId
              * @param accessKeySecret
              * @return Client
              * @throws Exception
              */
        private string AlibabaSend(string mobile, string code)
        {
            string accessKeyId = "LTAIn48snU1Cvudh", accessKeySecret = "occs4cCeawjBrFwmSoo8Em407avjaC";
            IClientProfile profile = DefaultProfile.GetProfile("cn-qingdao", accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";

            request.AddQueryParameters("PhoneNumbers", mobile);
            request.AddQueryParameters("TemplateCode", "SMS_206620463");
            request.AddQueryParameters("SignName", "心智趣味");
            request.AddQueryParameters("TemplateParam", "{\"code\":" + code + "}");
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                return response.Data;
                //Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }
            return "";
        }

        private int SendSmsVerify(string mobile, string type)
        {
            System.Random aa = new Random();
            int j = aa.Next(10000, 99999);
            Entity.Sms.SmsEntity sms = new Entity.Sms.SmsEntity();
            sms.Id = Guid.NewGuid().ToString("N");
            sms.Code = j.ToString();
            sms.Addtime = DateTime.Now;
            sms.Endtime = sms.Addtime.AddMinutes(30);
            sms.Mobile = mobile;
            sms.State = 0;
            sms.Type = type;

            string response = AlibabaSend(sms.Mobile, sms.Code);

            if (response == "")
            {
                return 0;
            }
            else
            {
                JObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(response);
                if (obj.Value<string>("Code") == "OK")
                {
                    return _repository.Insert(sms);

                }
                else
                {

                    return 0;
                }
            }

        }

        public IResultModel Send(string mobile, string type)
        {


            List<string> types = new List<string>() { "register" };

            if (!types.Contains(type))
            {
              return  ResultModel.Failed("错误的类型");

            }

            if (!RegexHelper.CheckInput(mobile, RegexHelper.IS_VALID_MOBILE))
            {
                return ResultModel.Failed("请输入正确的手机号码");


            }
            if (type == "register")
            {

                if (_agentRepository.Exists(a => a.AgentPhoneNum == mobile))
                {
                    return ResultModel.Failed("手机号码已被绑定");


                }
                

            }

            int result = SendSmsVerify(mobile, type);
            if (result == 0)
            {
                return ResultModel.Failed("短信发送失败");

            }
            else
            {
                return ResultModel.Success("短信发送成功");
            }

        }
    }
}
